﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using FeedReaderApp.Model;
using FeedReaderApp.ViewModel;
using GalaSoft.MvvmLight;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Search;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231

namespace FeedReaderApp
{
    public sealed partial class GroupedItemsPage : FeedReaderApp.Common.LayoutAwarePage
    {
        public GroupedItemsViewModel ViewModel { get; set; }

        public GroupedItemsPage()
        {
            this.InitializeComponent();

            if (!ViewModelBase.IsInDesignModeStatic)
            {
                ViewModel = new GroupedItemsViewModel();
                DataContext = ViewModel;
            }
        }

        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;
            ViewModel.Initialize();
        }

        protected override void SaveState(Dictionary<string, object> pageState)
        {
            DataTransferManager.GetForCurrentView().DataRequested -= OnDataRequested;
            ViewModel.DeRegisterDataSourceEvents();
        }

        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            try
            {
                ViewModel.Share(e);
            }
            catch
            {
            }
        }

        void Header_Click(object sender, RoutedEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            this.Frame.Navigate(typeof(GroupDetailPage), Constants.BlogPrefix + ((FeedGrouping)group).Name);
        }

        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var itemId = ((FeedItem)e.ClickedItem).UniqueId;
            this.Frame.Navigate(typeof(ItemDetailPage), itemId);
        }
    }
}
